import { Inject, Post, Body, Get, Query } from '@midwayjs/core';
import { CoolController, BaseController, CoolUrlTag, TagTypes, CoolTag } from '@cool-midway/core';
import { OrderOrderEntity } from '../../entity/order';
import { OrderOrderService } from '../../service/order';
import { OrderGoodsEntity } from '../../entity/goods';
import { OrderGoodsService } from '../../service/goods';
import { OrderShopEntity } from '../../entity/shop';
import { OrderShopService } from '../../service/shop';
import { OrderCityEntity } from '../../entity/city';
import { OrderCityService } from '../../service/city';
import { AppointmentInfoService } from '../../../appointment/service/info';
import { idText } from 'typescript';

/**
 * 订单信息
 */
@CoolUrlTag()
@CoolController({
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  entity: OrderOrderEntity,
  service: OrderOrderService,
  pageQueryOp: {
    keyWordLikeFields: ['a.orderNo'],
    fieldEq: ['a.payStatus', 'a.deliveryStatus'],
    select: ['a.*', 'GROUP_CONCAT(b.goodsName) AS goodsNames'],
    join: [
      {
        entity: OrderGoodsEntity,
        alias: 'b',
        condition: 'a.id = b.orderId',
        type: 'leftJoin',
      },
    ],
    extend: find => {
      find.groupBy('a.id');
      return find;
    },
    where: async ctx => {
      // 仅查询当前用户的订单
      const userId = ctx.user.id;
      return [['a.userId = :userId', { userId }]];
    },
  },
})
export class AppOrderOrderController extends BaseController {
  @Inject()
  orderOrderService: OrderOrderService;

  @Inject()
  orderGoodsService: OrderGoodsService;

  @Inject()
  orderShopService: OrderShopService;

  @Inject()
  orderCityService: OrderCityService;

  @Inject()
  appointmentInfoService: AppointmentInfoService;

  @Inject()
  ctx;

  // 生成订单
  @Post('/createOrderByGoodsIds')
  async createOrderByGoodsIds(@Body() body: { goodsIds: number[], shopId?: number }) {
    const { goodsIds, shopId } = body;
    const orderId = await this.orderOrderService.createOrderByGoodsIds(goodsIds, shopId);
    return this.ok({orderId: orderId});
  }

  // 生成订单
  @Post('/createOrderBuyOrUpGoods')
  async createOrderBuyOrUpGoods(@Body() body: { goodsIds: string; shopId?: number; filmCode?: string; lensQuantity?: number }) {
    const orderId = await this.orderOrderService.createOrderBuyOrUpGoods(body);
    return this.ok({orderId: orderId});
  }

  // 获取商品列表
  // @CoolTag(TagTypes.IGNORE_TOKEN)
  @Get('/goodsList')
  async goodsList(@Query('shopId') shopId?: number, @Query('sceneId') sceneId?: number) {
    if (!shopId) {
      shopId = 0;
    }
    if (!sceneId) {
      sceneId = 0;
    }
    return this.ok(await this.orderGoodsService.appIndexList(shopId, sceneId));
  }

  // 根据ID获取商品详情
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Get('/goodsDetail')
  async goodsDetail(@Query('id') id: number) {
    return this.ok(await this.orderGoodsService.appDetail(id));
  }

  // 根据ID获取商品详情
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Get('/goodsDetailV2')
  async goodsDetailV2(@Query('id') id: number) {
    return this.ok(await this.orderGoodsService.appDetailV2(id));
  }

  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Get('/goodsDetailV3')
  async goodsDetailV3(@Query('id') id: number) {
    return this.ok(await this.orderGoodsService.appDetailV3(id));
  }

  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Get('/getGoodsListById')
  async goodsListV2(@Query('goodsId') goodsId: number) {
    if (!goodsId) {
      throw new Error('商品ID不能为空');
    }
    return this.ok(await this.orderGoodsService.getGoodsListById(goodsId));
  }

  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/getGoodsMoneyByIds')
  async getGoodsMoneyByIds(@Body() body: { goodsIds: number[] }) {
    if (!body.goodsIds || body.goodsIds.length === 0) {
      throw new Error('商品ID不能为空');
    }
    return this.ok(await this.orderGoodsService.getGoodsMoneyByIds(body));
  }

  // 获取订单详情
  @Get('/getOrderInfo')
  async getOrderInfo(@Query('id') id: number) {
    return this.ok(await this.orderOrderService.getOrderInfo(id));
  }

  // 获取订单列表
  @Get('/getPaidOrders')
  async getPaidOrders() {
    return this.ok(await this.orderOrderService.getPaidOrders());
  }

  // 获取支付参数
  @Post('/getPayParams')
  async getPayParams(@Body('id') id: number, @Body('shopId') shopId: number) {
    return this.ok(await this.orderOrderService.getPayParams(id, shopId));
  }

  // 微信支付回调
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/handleWxPayNotify')
  async handleWxPayNotify(@Body() body: any) {
    return this.ok(await this.orderOrderService.handleWxPayNotify(body, 4));
  }

  // 亦庄店
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/handleWxPayNotifyYizhuangShuangBoShi')
  async handleWxPayNotifyByYizhuang(@Body() body: any) {
    return this.ok(await this.orderOrderService.handleWxPayNotify(body, 4));
  }

  // 福柏眼科
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/handleWxPayNotifyQingdaofubaiyanke')
  async handleWxPayNotifyQingdaofubaiyanke(@Body() body: any) {
    return this.ok(await this.orderOrderService.handleWxPayNotify(body, 16));
  }

  // 近停视界
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/handleWxPayNotifyWuhanjintingshijie')
  async handleWxPayNotifyWuhanjintingshijie(@Body() body: any) {
    return this.ok(await this.orderOrderService.handleWxPayNotify(body, 15));
  }

  // 武汉开叔医疗
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/handleWxPayNotifyWuhankaiushuyiliao')
  async handleWxPayNotifyWuhankaiushuyiliao(@Body() body: any) {
    return this.ok(await this.orderOrderService.handleWxPayNotify(body, 14));
  }

  // 盛大眼科
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/handleWxPayNotifyShengdayanke')
  async handleWxPayNotifyShengdayanke(@Body() body: any) {
    return this.ok(await this.orderOrderService.handleWxPayNotify(body, 20));
  }

  // 维儿目眼视光
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/handleWxPayNotifyWeiermuyanshiguang')
  async handleWxPayNotifyWeiermuyanshiguang(@Body() body: any) {
    return this.ok(await this.orderOrderService.handleWxPayNotify(body, 19));
  }

  // 大秦视界视光中心
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/handleWxPayNotifyDaqinshijie')
  async handleWxPayNotifyDaqinshijie(@Body() body: any) {
    return this.ok(await this.orderOrderService.handleWxPayNotify(body, 23));
  }

  //视医佳眼科诊所
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/handleWxPayNotifyShiyijiayankezhensuo')
  async handleWxPayNotifyShiyijiayankezhensuo(@Body() body: any) {
    return this.ok(await this.orderOrderService.handleWxPayNotify(body, 25));
  }

  //听澜互动 
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/handleWxPayNotifyTinglanhudong')
  async handleWxPayNotifyTinglanhudong(@Body() body: any) {
    return this.ok(await this.orderOrderService.handleWxPayNotify(body, 31));
  }

  // 直朴视光青少年近视防控中心
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/handleWxPayNotifyZhipushiguangqingshaonian')
  async handleWxPayNotifyZhipushiguangqingshaonian(@Body() body: any) {
    return this.ok(await this.orderOrderService.handleWxPayNotify(body, 34));
  }

  // 儿童青少年近视防控指导中心（齐鲁园）
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/handleWxPayNotifyErtongqingshaonianqiluyuan')
  async handleWxPayNotifyErtongqingshaonianqiluyuan(@Body() body: any) {
    return this.ok(await this.orderOrderService.handleWxPayNotify(body, 33));
  }

  // 儿童青少年近视防控指导中心（桃源中心）
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/handleWxPayNotifyErtongqingshaoniantaoyuan')
  async handleWxPayNotifyErtongqingshaoniantaoyuan(@Body() body: any) {
    return this.ok(await this.orderOrderService.handleWxPayNotify(body, 32));
  }

  // 成都高看一眼
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/handleWxPayNotifyGaokanyiyan')
  async handleWxPayNotifyGaokanyiyan(@Body() body: any) {
    return this.ok(await this.orderOrderService.handleWxPayNotify(body, 37));
  }

  // 滦洲
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/handleWxPayNotifyLuanzhouhaoxunjingyiyanjing')
  async handleWxPayNotifyLuanzhouhaoxunjingyiyanjing(@Body() body: any) {
    return this.ok(await this.orderOrderService.handleWxPayNotify(body, 49));
  }

  // 获取店铺列表
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Get('/getShopList')
  async getShopList(@Query('cityName') cityName: string) {
    return this.ok(await this.orderShopService.getShopList(cityName));
  }

  // 获取城市列表
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Get('/getCityList')
  async getCityList() {
    return this.ok(await this.orderCityService.getSelectList());
  }

  // 获取单个店铺信息
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Get('/getShopInfo')
  async getShopInfo(@Query('id') id: number) {
    return this.ok(await this.orderShopService.getShopInfo(id));
  }

  // 获取店铺可预约期数
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Get('/getOpenPeriods')
  async getOpenPeriods() {
    return this.ok(await this.orderShopService.getOpenPeriods());
  }

  // 获取店铺预约信息
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Get('/getAppointmentInfo')
  async getAppointmentInfo(@Query('shopId') shopId: number, @Query('date') date: string) {
    return this.ok(await this.orderShopService.getAppointmentInfo(shopId, date));
  }

  // 预约
  @Post('/appoint', { summary: '预约' })
  async appoint(
    @Body() param: {
      shopId: number;
      date: string;
      time: string;
      studentId?: number;
      doctorId?: number;
    }
  ) {
    param.studentId = this.ctx.user.id;
    param.doctorId = 0;
    const result = await this.appointmentInfoService.appoint(param);
    return this.ok(result);
  }


  // 获取邀请的基础信息
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Get('/getInviteInfo')
  async getInviteInfo() {
    return this.ok({
      'bottom_bg': 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/activeInvite/bottom_bg.jpg',
      'bottom_form': 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/activeInvite/bottom_form_2.png',
      'submit_btn_img': 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/invite_btn.png',
      'popup_title': '恭喜获得项目资格',
      'popup_subtitle': '',
      'popup_desc': '长按添加同仁主任助理微信',
      'bottom_from_top': '65vw',
    });
  }

  // 获取图片链接
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Get('/getImageUrl')
  async getImageUrl(@Query('imageName') imageName: string) {
    return this.ok({
      'appoiont_index_banner': 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/index2_appoint_banner.png',
      'appoint_detail': 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/appoint_detail2.jpeg',
    });
  }

  // 获取镜片参数
  @Post('/getOrderById')
  async getOrderById(@Body() body: { scanUrl: string }) {
    console.log('getOrderById', body.scanUrl);
    return this.ok(await this.orderOrderService.getOrderById(body.scanUrl));
  }

  // 检查scanUrl
  @Post('/checkScanUrl')
  async checkScanUrl(@Body() body: { scanUrl: string }) {
    return this.ok(await this.orderOrderService.checkScanUrl(body.scanUrl));
  }

  // 激活订单
  @Post('/activeOrder')
  async activeOrder(@Body() body: {
    name: string;
    birthDate: string;
    gender: string;
    scanLeft: string;
    scanRight: string;
  }) {
    return this.ok(await this.orderOrderService.activeOrder(body));
  }

  // 查询激活订单
  @Post('/queryActiveOrder')
  async queryActiveOrder(@Body() body: { scanUserId: number }) {
    return this.ok(await this.orderOrderService.queryActiveOrder(body));
  }

}
